package com.bs.auth.controller;

import com.bs.auth.utils.Assert;
import com.bs.common.utils.Result;
import com.bs.auth.vo.Oauth2TokenVo;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.endpoint.TokenEndpoint;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.security.Principal;
import java.util.HashMap;
import java.util.Map;

/**
 * @author bingshao
 * @date 2022/9/8
 **/
@RestController
@RequestMapping("/oauth")
public class LoginController {

    @Resource
    private TokenEndpoint tokenEndpoint;

    @GetMapping("/token")
    public Result<Oauth2TokenVo> getToken(Principal principal,
                                          @RequestParam String client_id,
                                          @RequestParam String client_secret,
                                          @RequestParam String grant_type,
                                          String username,
                                          String password,
                                          String phone,
                                          String code,
                                          String refresh_token,
                                          String scope,
                                          String redirect_uri) throws HttpRequestMethodNotSupportedException {

        Map<String, String> parameters = new HashMap<>(16);
        parameters.put("client_id", client_id);
        parameters.put("client_secret", client_secret);
        parameters.put("grant_type", grant_type);
        parameters.put("username", username);
        parameters.put("password", password);
        parameters.put("phone", phone);
        parameters.put("code", code);
        parameters.put("refresh_token", refresh_token);
        parameters.put("scope", scope);
        parameters.put("redirect_uri", redirect_uri);
        OAuth2AccessToken oAuth2AccessToken = tokenEndpoint.postAccessToken(principal, parameters).getBody();
        Assert.isNotNull(oAuth2AccessToken, "登陆失败");
        Oauth2TokenVo oauth2TokenVo = Oauth2TokenVo.builder()
                .accessToken(oAuth2AccessToken.getValue())
                .refreshToken(oAuth2AccessToken.getRefreshToken().getValue())
                .expiresIn(oAuth2AccessToken.getExpiresIn())
                .tokenHead("Bearer ").build();
        return Result.success(oauth2TokenVo);
    }

}
